package com.freewater.springboot.demo.spel.vars;

import com.freewater.springboot.demo.spel.Inventor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
        System.out.println(tesla.getName());

        EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
        context.setVariable("newName", "Mike Tesla");

        ExpressionParser parser = new SpelExpressionParser();
        parser.parseExpression("name = #newName").getValue(context, tesla);
        System.out.println(tesla.getName());  // "Mike Tesla"

        List<Integer> primes = new ArrayList<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17));
        context = SimpleEvaluationContext.forReadWriteDataBinding().build();
        context.setVariable("primes", primes);

        // all prime numbers > 10 from the list (using selection ?{...})
        // evaluates to [11, 13, 17]
        List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression("#primes.?[#this > 10]").getValue(context);
        System.out.println(primesGreaterThanTen);
    }
}
